﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NCRGEA.AAL;

using System.Data.SqlClient;

namespace NCRGEA.Admin
{
    public partial class frmBarcodeEntry : Form
    {
        #region Global Variables

        /// <summary>
        /// This is the number of days that the renewal date can be with and the user can make a payment
        /// </summary>
        const double renewalRange = -30;
        const int cBatchMax = 25;

        const int due = 1;
        const int cashPayMethod = 1;

        int batchID = 0;

        #endregion

        frmMain main = null;
        User currentUser = null;

        public frmBarcodeEntry()
        {
            Logger.Log("Barcode cash entry loaded");
            InitializeComponent();
            loadData();
        }

        #region Data Manipulation
        
        private void loadData()
        {
            string query = @"SELECT
                                MAX(p.BatchID) as hBatch
                            FROM
                                payments p";

            DataTable temp = DAL.ExecuteQuery(query);

            if (temp.Rows[0]["hBatch"].ToString() == string.Empty)
                batchID = 0;
            else
            {
                batchID = (int)temp.Rows[0]["hBatch"];
                batchID++;
            }
        }

        #endregion

        #region Control Manipulation

        /// <summary>
        /// Check to make sure that the member can actually make a payment
        /// </summary>
        /// <returns>Returns true if the member can make a payment, false if the cannot</returns>
        private bool checkMember()
        {
            string query = @"SELECT
                                *
                             FROM
                                memInfo mi
                                    INNER JOIN
                                        memTypes mt
                                    ON
                                        mi.TypeID = mt.TypeID
                             WHERE
                                mi.MemberID = @memberID";

            SqlParameter[] param = new SqlParameter[1];
            param[0] = new SqlParameter("@memberID", int.Parse(txtMemID.Text));
            
            Logger.Log("MemberID : " + int.Parse(txtMemID.Text));
            
            Logger.Log("Query: " + query);

            DataTable temp = DAL.ExecuteQuery(query,param);

            Logger.Log("Member Info table loaded.");

            foreach (DataRow row in temp.Rows)
            {
                string sTemp = row["Name"].ToString();

                if (doRenew(row, sTemp))
                {
                    Logger.Log("Processing payment. Method: checkMember().");

                    
                    DateTime nTime = DateTime.Today;

                    int staffID = ((frmMain)(this.MdiParent)).CurrentUser.StaffID;

                    try
                    {
                        if (UAL.SavePayment((int)row["MemberID"], cashPayMethod, null, double.Parse(txtAmount.Text), nTime, staffID, due))
                        {
                            batchMax();
                            updateRenewalDate(row);
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Log("Error occured while attempting to save a payment. Method: checkMember().: " + e.Message);
                    }

                    break;
                }
            }

            return true;
        }

        private void updateRenewalDate(DataRow row)
        {
            string nTime = row["RenewalDate"].ToString();
            
            DateTime temp;
            
            temp = DateTime.Parse(nTime);
            
            nTime = temp.Year + "/" + temp.Month + "/" + temp.Day;

            string query = @"UPDATE
                                memInfo
                            SET
                                RenewalDate = @RenewalDate
                            WHERE
                                MemberID = @MemberID";

            SqlParameter[] param = new SqlParameter[2];

            param[0] = new SqlParameter("@RenewalDate", nTime);
            param[1] = new SqlParameter("@MemberID", row["MemberID"]);

            DAL.ExecuteNonQuery(query, param);

            Logger.Log("Updated renewal date for: " + row["FirstName"].ToString() + " " + row["LastName"].ToString());
        }

        /// <summary>
        /// Used to determine whether the member can renew or no
        /// </summary>
        /// <returns>Returns true if the member can, false if they cannot.</returns>
        private bool doRenew(DataRow row, string sTemp)
        {
            if (sTemp == "LifeTime" || sTemp == "Deceased" || sTemp == "Removed" || sTemp == "Free")
            {
                MessageBox.Show("This member is unable to make payments.", "Member Payment Error");
                return false;
            }

            Logger.Log("Member is active. Still pending date");

            DateTime tTemp = (DateTime)row["RenewalDate"];
            TimeSpan range = DateTime.Today - tTemp;

            if (range.TotalDays < renewalRange)
            {
                Logger.Log("Comparing date, is not time for member to renew");
                MessageBox.Show("This member's renewal period is not up yet.", "Renewal Too Soon");
                return false;
            }

            Logger.Log("Member can be renewed. Method doRenew().");

            return true;
        }


        /// <summary>
        /// This method determines whether there are 25 members in this batch already
        /// </summary>
        /// <returns>True if there are 25 payments in this batch, false otherwise</returns>
        private bool batchMax()
        {
            string query = @"SELECT
                                COUNT(BatchID) as bCount
                            FROM
                                payments p
                            WHERE
                                BatchID =" + batchID;

            DataTable temp = DAL.ExecuteQuery(query);

            int bNum = -1;

            if (temp.Rows[0]["bCount"].ToString() == string.Empty)
                return false;
            else
                bNum = (int)temp.Rows[0]["bCount"];

            if (bNum + 1 > cBatchMax)
            {
                return true;
            }

            return false;
        }

        #endregion

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (validateTextBox())
            {
                Logger.Log("Starting Query.");
                if (checkMember())
                {
                    Logger.Log("Payment processed.");
                }
            }
            else
            {
                MessageBox.Show("Please enter monatary value.");
                Logger.Log("User: " + currentUser + " entered an invalid amount of: " + txtAmount.Text);
                txtAmount.Clear();                
            }
        }

        /// <summary>
        /// This will make sure that the input is a currentcy amount
        /// </summary>
        /// <returns>Returns true if it is currency, otherwise it returns false</returns>
        private bool validateTextBox()
        {
            double cash;
            int memID;

            if (double.TryParse(txtAmount.Text, out cash))
                return true;
            else
            {
                MessageBox.Show("Please enter a valid money amount.");
                return false;
            }

            if (txtMemID.Text != string.Empty && int.TryParse(txtMemID.Text, out memID))
                return true;
            else
            {
                MessageBox.Show("Please enter a memberID.");
            }

            return false; //It was not of currency
        }
    }
}
